﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Shared.Models;
using UwinEducation.Shared.Models.Auth;


namespace UwinEducation.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ApiControllerBase
    {
        private readonly IAuthService _authService;

        public AuthController(IAuthService authService)
        {
            _authService = authService;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">登录请求参数</param>
        /// <returns>返回用户信息</returns>
        [HttpPost("login")]
        public async Task<ApiResponse<TokenResponse>> Login([FromBody] LoginRequest request)
        {
            var token = await _authService.LoginAsync(request);
            return ApiResponse<TokenResponse>.Ok(token);
        }
        //[HttpPost("login")]
        //public async Task<IActionResult> Login([FromBody] LoginRequest request)
        //{
        //    var token = await _authService.LoginAsync(request);
        //    var result= Ok(token);
        //    return await Task.FromResult(result);
        //}

        /// <summary>
        /// 刷新令牌
        /// </summary>
        [Authorize]
        [HttpPost("refresh-token")]
        public async Task<ApiResponse<TokenResponse>> RefreshToken([FromBody] RefreshTokenRequest request)
        {
            var token = await _authService.RefreshTokenAsync(request.RefreshToken);
            return ApiResponse<TokenResponse>.Ok(token);
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        [Authorize]
        [HttpPost("logout")]
        public async Task<ApiResponse<bool>> Logout()
        {
            var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            await _authService.LogoutAsync(token);
            return ApiResponse<bool>.Ok(true, "注销成功");
        }
    }
}
